package com.jh3502.vivo.net;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public final class ApiClient {
    private static final String TAG = "ApiClient";

    public static ApiList apiList;

    public static ApiConfiguration configuration;

    private static long TIME_OUT = 1000 * 60;

    public static void init(ApiConfiguration apiConfiguration) {
        configuration = apiConfiguration;
        String apiHost = ApiConstants.sChooseApi(configuration.getDataSourceType());
        apiList = initApiService(apiHost, ApiList.class);
    }

    private static <T> T initApiService(String baseUrl, Class<T> clazz) {

        OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
        OkHttpClient client = builder
                .connectTimeout(TIME_OUT, TimeUnit.MILLISECONDS)
                .readTimeout(TIME_OUT, TimeUnit.MILLISECONDS)
                .writeTimeout(TIME_OUT, TimeUnit.MILLISECONDS)
                .addInterceptor(chain -> {
                    Request request = chain.request().newBuilder().build();
                    return chain.proceed(request);
                })
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();

        return retrofit.create(clazz);
    }
}
